package com.iseastar.guojiang.newcabinet;

import android.content.Intent;
import android.os.Message;

import com.amap.api.location.AMapLocation;
import com.baidu.mapapi.model.LatLng;
import com.iseastar.guojiang.BeeApplication;
import com.iseastar.guojiang.MainActivity;
import com.iseastar.guojiang.app.AppCache;
import com.iseastar.guojiang.app.Intents;
import com.iseastar.guojiang.app.TimerService;
import com.iseastar.guojiang.loc.AppBackgroundService;
import com.iseastar.guojiang.loc.CourierLocationService;
import com.iseastar.guojiang.logic.AppHttp;
import com.iseastar.guojiang.logic.AppLogic;
import com.iseastar.guojiang.logic.JSON;
import com.iseastar.guojiang.model.CourierTaskEventCommon;
import com.iseastar.guojiang.model.PassportTaskBackBean;
import com.iseastar.guojiang.model.ReqResult;
import com.iseastar.guojiang.model.ServiceTaskBean;
import com.iseastar.guojiang.util.LocationUtils;
import com.iseastar.guojiang.util.PollingUtils;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;

import droid.frame.Config;
import droid.frame.activity.ActivityMgr;
import droid.frame.push.PushInterface;
import droid.frame.service.BaseService;
import droid.frame.utils.Android;
import droid.frame.utils.android.DataCleanManager;
import droid.frame.utils.android.Log;
import droid.frame.utils.android.Notify;
import droid.frame.utils.lang.ScreenListener;
import droid.frame.utils.lang.Str;

/**
 * Created by joker on 2018/5/9.
 * 用来处理火箭侠首页任务列表数据
 * 1.启动首页并且是开工和接单状态的时候，启动当前的service
 * 2.启动 {@link com.iseastar.guojiang.loc.CourierLocationService} 进行定位，并且上传坐标
 * 3.检查上传返回来的数据，如果token失效，那么通知应用退出登录
 */
public class DealTaskService extends BaseService {

    private AMapLocation aMapLocation = null;
    private ScreenListener screenListener = null;
    private boolean isStop = false;

    @Override
    public void onCreate() {
        super.onCreate();
        Notify.getInstance().startForeground(this);
    }

    @Override
    public int onStartCommand(final Intent intent, int flags, int startId) {
        if (intent != null) {
            isStop = intent.getBooleanExtra("isStop", false);
        }
        if (screenListener == null) {
            screenListener = new ScreenListener(getApplicationContext());
        }
        screenListener.begin(new ScreenListener.ScreenStateListener() {
            @Override
            public void onScreenOn() {
                // 开屏
                Log.d("33333", "开屏");
                //屏幕亮时，应用处于后台运行，并且定位不存在，那么启动定位，并且销毁锁屏时的KeepScreenOnActivity
//                if (!Android.isAppOnForeground(getApplication())) {
//                    AppLogic.courierBackToHomeAndRefresh(getApplication());
//                } else {
//                    PollingUtils.stopPollingService(getApplication(), TimerService.class, TimerService.ACTION);
//                }
//                writerLogToFile("屏幕开屏...");
                if (Android.isAppOnForeground(getApplication())) {
                    PollingUtils.stopPollingService(getApplication(), TimerService.class, TimerService.ACTION);
                } else {
                    startWorkLocation(false);
                }
            }

            @Override
            public void onScreenOff() {
                // 锁屏
                Log.d("33333", "锁屏");
//                if (ActivityMgr.isActivityRunning(getApplication(), KeepScreenOnActivity.class) && KeepScreenOnActivity.instance != null) {
//                    KeepScreenOnActivity.instance.finish();
//                }
//                Intent startIntent = new Intent(getApplication(), KeepScreenOnActivity.class);
//                startIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                startActivity(startIntent);
                PollingUtils.startPollingService(getApplication(), 10, TimerService.class, TimerService.ACTION);
            }

            @Override
            public void onUserPresent() {
                // 解锁
                Log.d("33333", "解锁");
            }
        });
        startWorkLocation(isStop);
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            //上传火箭侠位置返回,每20秒上传一次位置
            case com.iseastar.guojiang.consts.MsgID.courier_location_upload_data:
                aMapLocation = (AMapLocation) msg.obj;
                MainActivity.aMapLocation = aMapLocation;
                Log.d("33333", "定位返回:" + aMapLocation.getCity());
                if (null != aMapLocation && Str.isNotEmpty(aMapLocation.getCity())) {
                    LatLng dPoint = LocationUtils.locationConvert(aMapLocation);
                    if (dPoint != null) {
//                        writerLogToFile("正常调用坐标上传");
                        AppHttp.getInstance().uploadCourierLocation(dPoint.latitude, dPoint.longitude);
                    } else {
//                        if (aMapLocation != null) {
//                            writerLogToFile("坐标转换异常,坐标不为空,lat:" + aMapLocation.getLatitude() + ",lng:" + aMapLocation.getLongitude());
//                        } else {
//                            writerLogToFile("坐标转换异常,坐标为空");
//                        }
                        showToast("坐标转换异常");
                    }
                } else {
//                    writerLogToFile("定位失败");
                    if (aMapLocation != null && aMapLocation.getErrorCode() == 4) {
                        showToast("当前网络不稳定");
                    }
                }
                return true;
            //刷新火箭侠位置返回的数据
            case com.iseastar.guojiang.consts.MsgID.courier_location_refresh:
                ReqResult<PassportTaskBackBean> reqResult = JSON.parser(msg.obj, PassportTaskBackBean.class);
//                writerLogToFile("调用上传坐标接口返回");
                if (checkLoginStatus(reqResult)) {
                    PassportTaskBackBean backBean = reqResult.getResult();
                    if (backBean != null) {
                        ServiceTaskBean newTaskBean = backBean.getTaskBean();
                        int newTaskCount = backBean.getNewTaskCnt();
                        if (newTaskBean != null) {
                            newTaskBean.setNewTaskCnt(newTaskCount);
                            newTaskBean.setPassportType(0);
                            AppLogic.getPassportList().add(newTaskBean);
                            AppLogic.getAppBackgroundPassportList().add(newTaskBean);
                        }
                        ArrayList<ServiceTaskBean> cancelList = backBean.getCancelList();
                        if (cancelList != null && cancelList.size() > 0) {
                            for (int i = 0; i < cancelList.size(); i++) {
                                ServiceTaskBean bean = cancelList.get(i);
                                bean.setPassportType(1);
                                bean.setNewTaskCnt(0);
                                AppLogic.getPassportList().add(bean);
                                AppLogic.getAppBackgroundPassportList().add(bean);
                            }
                        }
                        //先进性判断当前应用是否处于后台运行，如果处于后台运行则再service中进行震动，响铃提示
                        if (!Android.isAppOnForeground(BeeApplication.getContext())) {
                            if (AppLogic.getAppBackgroundPassportList().size() > 0) {
                                Intent intent = new Intent();
                                intent.setClass(getApplication(), AppBackgroundService.class);
                                intent.setPackage(getPackageName());
                                startService(intent);
                            }
                        } else {
                            if (ActivityMgr.isServiceRunning(BeeApplication.getContext(), "com.iseastar.guojiang.loc.AppBackgroundService")) {
                                Intent intent = new Intent();
                                intent.setClass(getApplication(), AppBackgroundService.class);
                                intent.setPackage(getPackageName());
                                stopService(intent);
                            }
                            /**
                             * 通知 {@link com.iseastar.guojiang.MainActivity} 刷新界面，处理数据
                             */
                            if (newTaskBean != null || (cancelList != null && cancelList.size() > 0)) {
                                EventBus.getDefault().post(new CourierTaskEventCommon(backBean));
                            }
                        }
                    }
                } else {
                    showToast(reqResult.getMessage());
                }
                return true;
        }
        return false;
    }

//    public static void writerLogToFile(String content) {
//        try {
//            File temp = new File(AppConfig.getCrashDir() + "/Logs/");// 自已缓存文件夹
//            if (!temp.exists()) {
//                temp.mkdir();
//            }
//            FileWriter fw = new FileWriter(temp.getAbsolutePath()
//                    + "/log.txt", true);
//            if (fw != null) {
//                fw.flush();
//                fw.write(DateUtils.getTimeYMDHMSFormat().format(new Date()));
//                fw.write("  ," + content);
//                fw.write("\n");
//                fw.close();
//            }
//        } catch (Exception e1) {
//            e1.printStackTrace();
//        }
//    }

    /**
     * 检测是否在其他设备上进行过登录
     *
     * @param result
     * @return
     */
    private boolean checkLoginStatus(ReqResult result) {
        if (result.isSuccess()) {
            return true;
        }
        //其他设备已经登录了
        else if (result.getStatus() == 10000) {
            startWorkLocation(true);
            stopSelf();
            try {
                AppLogic.logoutDealService(getApplication());
                PushInterface.logout();
            } catch (Exception e) {
                e.printStackTrace();
            }
            new DataCleanManager().cleanApplicationData(getApplication(), Config.getMainDiar());
            AppCache.setUser(null);
            AppCache.setOrder(null);
            AppCache.setStationOpenInfoBean(null);
            ActivityMgr.finishAll();
            Intents.startLauncherActivity1(getApplication());
            return false;
        } else {
            return false;
        }
    }

    /**
     * 开启轮询定位
     *
     * @param isStop true 关闭定位 false 打开定位
     */
    public static synchronized void startWorkLocation(boolean isStop) {
        if (!ActivityMgr.isServiceRunning(BeeApplication.getContext(), "com.iseastar.guojiang.loc.CourierLocationService") && !isStop) {
            Intent intent = new Intent();
            intent.setClass(BeeApplication.getContext(), CourierLocationService.class);
            intent.putExtra("msgId", com.iseastar.guojiang.consts.MsgID.courier_location_upload_data);
            BeeApplication.getContext().startService(intent);
        } else {
            if (isStop) {
                Intent intent = new Intent();
                intent.setClass(BeeApplication.getContext(), CourierLocationService.class);
                intent.putExtra("msgId", com.iseastar.guojiang.consts.MsgID.courier_location_upload_data);
                BeeApplication.getContext().stopService(intent);
            }
        }
    }

    @Override
    public void onDestroy() {
        if (screenListener != null) {
            screenListener.unregisterListener();
        }
        super.onDestroy();
    }
}
